package cn.hchaojie.lucene;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.LongPoint;
import org.apache.lucene.document.StoredField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.store.FSDirectory;

import com.hankcs.lucene.HanLPAnalyzer;

public class LuceneDirectoryIndexer {
	private static final String DATA_PATH = "D:\\workspace\\workspace_stxy\\lucene-day02\\data";
	private static final String INDEX_PATH = "D:\\workspace\\workspace_stxy\\lucene-day02\\index";
	public static void main(String[] args) throws IOException {
		// 把目录里面的文件都遍历出来
		// File file = new File(DATA_PATH);
		// File[] files = file.listFiles();	// 列出目录下的所有文件
		
		List<File> files = new ArrayList<>();
		// 遍历文件（遍历目录和子目录，速度非常快）
		Files.walkFileTree(Paths.get(DATA_PATH), new SimpleFileVisitor<Path>() {
			// 遍历到每个文件的时候，visitFile方法都会被调用
			@Override
			public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
				files.add(file.toFile());
				
				return FileVisitResult.CONTINUE;
			}
		});
		
		// 对每个文件进行索引
		IndexWriter indexWriter = createIndexWriter();
		for (File f : files) {
			indexWriter.addDocument(convertToDocument(f));
		}
		
		indexWriter.close();
	}

	// 创建一个索引写入器
	private static IndexWriter createIndexWriter() throws IOException {
		IndexWriter indexWriter = new IndexWriter(
				FSDirectory.open(Paths.get(INDEX_PATH)), 
				new IndexWriterConfig(new StandardAnalyzer()));
//				new IndexWriterConfig(new HanLPAnalyzer()));
		return indexWriter;
	}

	// 把原始的文档转化成Document对象
	private static Document convertToDocument(File file) throws FileNotFoundException {
		Document doc = new Document();
		
		// 把文件的每一个信息封装到Field对象里面去
		// 名字、路径、大小、内容
		
		Field nameField = new TextField("name", file.getName(), Store.YES);
		Field pathField = new StoredField("path", file.getAbsolutePath());
		Field sizeField = new LongPoint("size", file.length());
		Field sizeStoredField = new StoredField("size", file.length());
		Field contentField = new TextField("content", new BufferedReader(new FileReader(file)));
		
		doc.add(nameField);
		doc.add(pathField);
		doc.add(sizeField);
		doc.add(sizeStoredField);
		doc.add(contentField);

		return doc;
	}
}
